# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mygongzhong.models import WxUsers, WxEvents, token
import requests
import json
import time

def gettoken():
    newtoken = token.objects.get(id=1).token
    return newtoken


def getuserinfo(openid):
    token = gettoken()
    url = "https://api.weixin.qq.com/cgi-bin/user/info"
    args = {"access_token": token, "openid": openid, "lang": "zh_CN"}
    re = requests.get(url, params=args)
    userdata = json.loads(re.text)
    return userdata


class Createmsg():
    def __init__(self, FromUserName, ToUserName):
        self.FromUserName = FromUserName
        self.ToUserName = ToUserName

    def t_text(self, msg):
        text = '<xml>\
               <ToUserName><![CDATA[' + self.FromUserName + ']]></ToUserName>\
               <FromUserName><![CDATA[' + self.ToUserName + ']]></FromUserName>\
               <CreateTime>' + str(int(time.time())) + '</CreateTime>\
               <MsgType><![CDATA[text]]></MsgType>\
               <Content><![CDATA[' + msg + ']]></Content>\
               </xml>'
        return text

    def t_news(self, title, description, picurl, url):
        text = '<xml>\
           <ToUserName><![CDATA[' + self.FromUserName + ']]></ToUserName>\
           <FromUserName><![CDATA[' + self.ToUserName + ']]></FromUserName>\
           <CreateTime>' + str(int(time.time())) + '</CreateTime>\
           <MsgType><![CDATA[news]]></MsgType>\
           <ArticleCount>1</ArticleCount>\
           <Articles>\
           <item>\
           <Title><![CDATA[' + title + ']]></Title>\
           <Description><![CDATA[' + description + ']]></Description>\
           <PicUrl><![CDATA[' + picurl + ']]></PicUrl>\
           <Url><![CDATA[' + url + ']]></Url>\
           </item>\
           </Articles>\
           </xml>'
        return text


class CreateSource():
    def __init__(self, title, thumb_media_id, author, digest, show_cover_pic, content, content_source_url):
        self.title = title
        self.thumb_media_id = thumb_media_id
        self.author = author
        self.digest = digest
        self.show_cover_pic = show_cover_pic
        self.content = content
        self.content_source_url = content_source_url
    def s_lang_news(self):
        data = {
              "articles": [{
                   "title": self.title,
                   "thumb_media_id": self.thumb_media_id,
                   "author": self.author,
                   "digest": self.digest,
                   "show_cover_pic": self.show_cover_pic,
                   "content": self.content,
                   "content_source_url": self.content_source_url
                },

             ]
            }
        token = gettoken()
        url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token='+token
        pdata = json.dumps(data, ensure_ascii=False).encode('utf8')
        res = requests.post(url, data=pdata)
        print res.text
        return res.text

